# -*- coding:UTF-8 -*-
# file   : VideoSplitter.py
# time   : 2023/12/11 
# author : panghu
# Desc   :
import math
import sys
import threading
from PySide6.QtWidgets import QApplication, QMainWindow, QPushButton, QMessageBox
from PySide6.QtCore import Signal, QObject
from moviepy.video.io.VideoFileClip import VideoFileClip

from FileChooser import get_filename_and_extension


def get_video(file_path):
    video = VideoFileClip(file_path)
    return video, video.duration


def split_video_duration(file_path, clip_duration):
    video, video_duration = get_video(file_path)
    # 计算片段数量
    num_clips = math.ceil(video_duration / clip_duration)
    file_name, file_ext, folder_path = get_filename_and_extension(file_path)
    # 切割视频并保存
    for i in range(num_clips):
        start = i * clip_duration
        end = min((i + 1) * clip_duration, video_duration)
        try:
            clip = video.subclip(start, end)
        except:
            continue
        try:
            clip.write_videofile(f"{folder_path}{file_name}_{i + 1}.mp4")
        except:
            continue


def timestamp_to_seconds(timestamp):
    hours, minutes, seconds = timestamp.split(':')
    seconds, milliseconds = seconds.split(',')
    return int(hours) * 3600 + int(minutes) * 60 + int(seconds) + int(milliseconds) / 1000


def split_video_by_subtitles(file_path, subtitles):
    video = VideoFileClip(file_path)
    file_name, file_ext, folder_path = get_filename_and_extension(file_path)

    for i, (start, end, text) in enumerate(subtitles):
        # 将时间戳转换为秒
        start_seconds = timestamp_to_seconds(start)
        end_seconds = timestamp_to_seconds(end)

        # 切割视频
        segment = video.subclip(start_seconds, end_seconds)
        segment.write_videofile(f"{folder_path}{file_name}_{i + 1}.mp4")


def split_video_num(file_path, num_segments):
    video, video_duration = get_video(file_path)
    segment_duration = video_duration / num_segments
    file_name, file_ext, folder_path = get_filename_and_extension(file_path)
    # 切割视频并保存每个片段
    for i in range(num_segments):
        start_time = i * segment_duration
        end_time = min((i + 1) * segment_duration, video_duration)
        segment = video.subclip(start_time, end_time)
        segment.write_videofile(f"{folder_path}{file_name}_{i + 1}.mp4")


class VideoSplitter(QObject):
    finished = Signal(dict)  # 添加了一个字符串参数的信号

    def split_duration(self, file_path, clip_duration):
        info = {
            "task": "split_video_duration"
        }
        try:
            split_video_duration(file_path, clip_duration)
            info["isSuccess"] = True
        except:
            info["isSuccess"] = False
        self.finished.emit(info)

    def split_num(self, file_path, segment_num):
        info = {
            "task": "split_video_num"
        }
        try:
            split_video_num(file_path, segment_num)
            info["isSuccess"] = True
        except:
            info["isSuccess"] = False
        self.finished.emit(info)

    def split_srt(self, file_path, subtitles):
        info = {
            "task": "split_video_srt"
        }
        try:
            split_video_by_subtitles(file_path, subtitles)
            info["isSuccess"] = True
        except:
            info["isSuccess"] = False
        self.finished.emit(info)
